<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.list.searchTable']" />
    <a-card class="general-card" :title="$t('menu.list.searchTable')">
      <!-- 搜索表单 -->
      <SearchForm v-model="formModel" :sex-options="sexOptions" :status-options="statusOptions" @search="search" @reset="reset" />
      <a-divider style="margin-top: 0" />

      <!-- 表格工具栏 -->
      <TableToolbar
          :size="size"
          :show-columns="showColumns"
          :clone-columns="cloneColumns"
          :density-list="densityList"
          @update:size="size = $event"
          @update:clone-columns="cloneColumns = $event"
          @update:show-columns="showColumns = $event"
          @popup-visible-change="popupVisibleChange"
          @create="handleCreate"
          @import="handleImport"
          @download="handleDownload"
          @refresh="search"
      />

      <!-- 会员数据表格 -->
      <MemberTable
          :loading="loading"
          :data="renderData"
          :pagination="pagination"
          :clone-columns="cloneColumns"
          :size="size"
          @page-change="onPageChange"
          @view="handleView"
          @edit="handleEdit"
          @toggle-status="handleToggleStatus"
          @delete="handleDelete"
      />
    </a-card>

    <!-- 会员详情对话框 -->
    <MemberDetailModal
        v-model:visible="detailVisible"
        :member="currentDetailMember"
        @edit="handleEdit"
        @toggle-status="handleToggleStatus"
    />

    <!-- 会员编辑对话框 -->
    <MemberEditModal v-model:visible="editVisible" :member="editForm" @submit="handleEditSubmit" />

    <!-- 删除确认对话框 -->
    <DeleteConfirmModal v-model:visible="deleteVisible" :member="currentMember" @confirm="handleDeleteConfirm" />

    <!-- 启用/禁用确认对话框 -->
    <StatusConfirmModal
        v-model:visible="toggleStatusVisible"
        :member="currentMember"
        :status-action="statusAction"
        @confirm="handleToggleStatusConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import useLoading from '@/hooks/loading'
import {
  queryMemberPage,
  getMemberDetail,
  updateMember,
  toggleMemberStatus,
  deleteMember,
  MemberRecord,
  PageQuery,
  MemberDetail,
} from '@/api/member'
import { Pagination } from '@/types/global'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { DescData } from '@arco-design/web-vue/es/descriptions/interface'
import cloneDeep from 'lodash/cloneDeep'
import Sortable from 'sortablejs'
import { Message } from '@arco-design/web-vue'

// 导入拆分出的组件
import SearchForm from './components/SearchForm.vue'
import TableToolbar from './components/TableToolbar.vue'
import MemberTable from './components/MemberTable.vue'
import MemberDetailModal from './components/MemberDetailModal.vue'
import MemberEditModal from './components/MemberEditModal.vue'
import DeleteConfirmModal from './components/DeleteConfirmModal.vue'
import StatusConfirmModal from './components/StatusConfirmModal.vue'

// 定义表格密度类型
type SizeProps = 'mini' | 'small' | 'medium' | 'large'
type Column = TableColumnData & { checked?: true }

// 性别选项
const sexOptions = [
  { label: '男', value: true },
  { label: '女', value: false },
]

// 状态选项
const statusOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false },
]

// 表格密度选项
const densityList = [
  { name: '迷你', value: 'mini' },
  { name: '小号', value: 'small' },
  { name: '中等', value: 'medium' },
  { name: '大号', value: 'large' },
]

const generateFormModel = () => {
  return {
    trueName: '',
    mobile: '',
    sex: '',
    status: '',
    email: '',
  }
}

const { loading, setLoading } = useLoading(true)
const { t } = useI18n()
const renderData = ref<MemberRecord[]>([])
const formModel = ref(generateFormModel())
const cloneColumns = ref<Column[]>([])
const showColumns = ref<Column[]>([])

// 定义表格列
const columns = ref<Column[]>([
  {
    title: '#',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
  },
  {
    title: '姓名',
    dataIndex: 'trueName',
    width: 120,
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    width: 150,
  },
  {
    title: '性别',
    dataIndex: 'sex',
    slotName: 'sex',
    width: 80,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 180,
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
  },
  {
    title: '注册时间',
    dataIndex: 'time',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 240,
  },
])

// 对话框可见性控制
const detailVisible = ref(false)
const editVisible = ref(false)
const deleteVisible = ref(false)
const toggleStatusVisible = ref(false)

// 当前操作的会员数据
const currentMember = ref<MemberRecord | null>(null)
const currentDetailMember = ref<MemberDetail | null>(null)
const statusAction = ref(false) // true表示禁用操作，false表示启用操作
const editForm = ref<MemberDetail>({
  userId: 0,
  trueName: '',
  mobile: '',
  sex: true,
  status: true,
  email: '',
})

// 会员详情数据
const detailData = ref<DescData[]>([])

const size = ref<SizeProps>('medium')

const basePagination: Pagination = {
  current: 1,
  pageSize: 3,
}
const pagination = reactive({
  ...basePagination,
})

// 处理新增会员按钮点击
const handleCreate = () => {
  editForm.value = {
    userId: 0,
    trueName: '',
    mobile: '',
    sex: true,
    status: true,
    email: '',
  }
  editVisible.value = true
}

// 处理导入按钮点击
const handleImport = (event: any) => {
  // 处理文件导入逻辑
  Message.info('导入功能待实现')
}

// 处理下载按钮点击
const handleDownload = () => {
  // 处理下载逻辑
  Message.info('下载功能待实现')
}

// 查看会员详情
const handleView = async (record: MemberRecord) => {
  setLoading(true)
  try {
    const response = await getMemberDetail(record.userId)
    currentDetailMember.value = response.data
    detailVisible.value = true
  } catch (error) {
    Message.error('获取会员详情失败')
    console.error('获取会员详情失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理编辑按钮点击
const handleEdit = async (record: MemberRecord) => {
  setLoading(true)
  try {
    const response = await getMemberDetail(record.userId)
    editForm.value = response.data
    editVisible.value = true
  } catch (error) {
    Message.error('获取会员信息失败')
    console.error('获取会员信息失败:', error)
  } finally {
    setLoading(false)
  }
}

// 提交编辑表单
const handleEditSubmit = async () => {
  setLoading(true)
  try {
    await updateMember(editForm.value)
    Message.success('保存成功')
    editVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('保存失败')
    console.error('保存失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理禁用/启用按钮点击
const handleToggleStatus = (record: MemberRecord) => {
  currentMember.value = record
  statusAction.value = record.status
  toggleStatusVisible.value = true
}

// 确认禁用/启用
const handleToggleStatusConfirm = async () => {
  if (!currentMember.value) return

  const action = statusAction.value ? '禁用' : '启用'

  try {
    await toggleMemberStatus(currentMember.value.userId)
    Message.success(`${action}成功`)
    toggleStatusVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error(`${action}失败`)
    console.error(`${action}失败:`, error)
  }
}

// 处理删除按钮点击
const handleDelete = (record: MemberRecord) => {
  currentMember.value = record
  deleteVisible.value = true
}

// 确认删除
const handleDeleteConfirm = async () => {
  if (!currentMember.value) return

  try {
    await deleteMember([currentMember.value.userId])
    Message.success('删除成功')
    deleteVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('删除失败')
    console.error('删除失败:', error)
  }
}

const fetchData = async (params: PageQuery = { current: 1, pageSize: 20 }) => {
  setLoading(true)
  try {
    const response = await queryMemberPage(params)
    renderData.value = response.list
    pagination.current = params.current
    pagination.total = response.total
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false)
  }
}

const search = () => {
  const params = {
    ...basePagination,
    ...Object.entries(formModel.value).reduce(
        (acc, [key, value]) => {
          if (value !== '' && value !== undefined && value !== null) {
            acc[key] = value
          }
          return acc
        },
        {} as Record<string, any>
    ),
  }

  fetchData(params as PageQuery)
}

const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current })
}

fetchData()

const reset = () => {
  formModel.value = generateFormModel()
}

const exchangeArray = <T extends Array<any>>(array: T, beforeIdx: number, newIdx: number, isDeep = false): T => {
  const newArray = isDeep ? cloneDeep(array) : array
  if (beforeIdx > -1 && newIdx > -1) {
    newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop())
  }
  return newArray
}

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e
          exchangeArray(cloneColumns.value, oldIndex, newIndex)
          exchangeArray(showColumns.value, oldIndex, newIndex)
        },
      })
    })
  }
}

watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val)
      cloneColumns.value.forEach((item, index) => {
        item.checked = true
      })
      showColumns.value = cloneDeep(cloneColumns.value)
    },
    { deep: true, immediate: true }
)
</script>

<script lang="ts">
export default {
  name: 'MemberTable',
}
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
